#!/usr/bin/env python
# -*- coding: UTF-8 -*-

'''Generate a picture for each Elementary Cellular Automata

   http://en.wikipedia.org/wiki/Cellular_automaton#Elementary_cellular_automata'''

import os

from cellular_automata.elementary import ElementaryCellularAutomata

import pygame
from pygame.locals import *

pygame.init()

TILE_SIZE = (18, 18)

COLOR_ALIVE = (0, 0, 0)
COLOR_DEAD = (255, 255, 255)
COLOR_BORDER = (100, 100, 100)

ALIVE_IMAGE = pygame.Surface(TILE_SIZE)
ALIVE_IMAGE.fill(COLOR_ALIVE)
pygame.draw.rect(ALIVE_IMAGE, COLOR_BORDER, ALIVE_IMAGE.get_rect(), 1)

# Max Surface size is 16384 x 16384, 8191 rows exceeds that even with 1px tiles
MAX_ROWS = 30
IMAGE_FOLDER = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                            'images')

if not os.path.isdir(IMAGE_FOLDER):
    os.makedirs(IMAGE_FOLDER)


def get_rows_for_rule(starting_row, length, rule):
    ca = ElementaryCellularAutomata(rule, starting_row=starting_row)

    for _ in range(length):
        ca.game_loop()

    return ca


def make_picture(elementary, rule):
    max_length = elementary.width
    tile_width, tile_height = TILE_SIZE

    surface_width = max_length * tile_width
    surface_height = len(elementary.rows) * tile_height + tile_height

    surface = pygame.Surface((surface_width, surface_height))
    surface.fill(COLOR_DEAD)

    y_mod = 1
    for row in elementary.rows:
        for x_mod, char in enumerate(row):
            if char == '1':
                position = x_mod * tile_width, y_mod * tile_height

                surface.blit(ALIVE_IMAGE, position)

        y_mod += 1

    filename = 'rule_%s.png' % rule.zfill(3)
    image_path = os.path.join(IMAGE_FOLDER, filename)
    pygame.image.save(surface, image_path)

    print('Saved %s' % filename)

if __name__ == '__main__':
    # Random but(t) fun!
    starting_row = ElementaryCellularAutomata.get_random_row(30)

    print('Starting row: "%s"' % starting_row[0])
    for rule_dec in range(257):
        ca = get_rows_for_rule(starting_row, MAX_ROWS, rule_dec)
        make_picture(ca, str(rule_dec))
